import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import {
  type SettingContextType,
  type SettingContextState,
  SettingTabType,
  ConnectionTestStatus,
  SaveSettingsStatus,
  type ModelSettings,
  type GeneralSettings,
  type AdvancedSettings,
  type SystemSettings
} from '@/types/setting';

import {
  mockTestConnection,
  mockSaveSettings,
  getSettings
} from '@/api/setting';

const defaultSettings: SystemSettings = {
  model: {
    apiUrl: 'https://api.deepseek.com/v1',
    apiKey: '',
    model: 'deepseek-chat',
  },
  general: {
    language: 'zh-CN',
    theme: 'system'
  },
  advanced: {
    maxTokens: 2048,
    temperature: 0.7
  }
};

// 创建设置上下文
const SettingContext = createContext<SettingContextType | undefined>(undefined);

// 初始上下文状态
const initialState: SettingContextState = {
  settings: defaultSettings,
  originalSettings: defaultSettings,
  hasUnsavedChanges: false,
  activeTab: SettingTabType.MODEL,
  isOpen: false,
  showApiKey: false,
  connectionTestStatus: ConnectionTestStatus.IDLE,
  saveStatus: SaveSettingsStatus.IDLE
};

const loadSettingsFromStorage = async (): Promise<SystemSettings> => {
  try {
    const savedSettings = await getSettings();
    if (savedSettings && savedSettings.length > 0) {
      return savedSettings[0];
    }
  } catch (error) {
    console.error('加载设置失败:', error);
  }
  
  return defaultSettings;
};

export const SettingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  // 状态管理
  const [state, setState] = useState<SettingContextState>(initialState);

  // 初始化时从本地存储加载设置
  useEffect(() => {
    const loadSettings = async () => {
      const loadedSettings = await loadSettingsFromStorage();
        setState(prev => ({
        ...prev,
        settings: loadedSettings,
        originalSettings: loadedSettings
      }));
    };
  
    loadSettings();
  }, []);

  // 检查是否有未保存的更改
  useEffect(() => {
    const hasChanges = JSON.stringify(state.settings) !== JSON.stringify(state.originalSettings);
    if (hasChanges !== state.hasUnsavedChanges) {
      setState(prev => ({ ...prev, hasUnsavedChanges: hasChanges }));
    }
  }, [state.settings, state.originalSettings, state.hasUnsavedChanges]);

  // 打开设置弹窗
  const openSettings = useCallback(() => {
    setState(prev => ({ ...prev, isOpen: true }));
  }, []);

  // 关闭设置弹窗
  const closeSettings = useCallback(() => {
    setState(prev => ({ 
      ...prev, 
      isOpen: false,
      // 重置状态
      connectionTestStatus: ConnectionTestStatus.IDLE,
      saveStatus: SaveSettingsStatus.IDLE
    }));
  }, []);

  // 切换标签页
  const setActiveTab = useCallback((tab: SettingTabType) => {
    setState(prev => ({ ...prev, activeTab: tab }));
  }, []);

  // 更新模型设置
  const updateModelSettings = useCallback((modelSettings: Partial<ModelSettings>) => {
    setState(prev => ({
      ...prev,
      settings: {
        ...prev.settings,
        model: {
          ...prev.settings.model,
          ...modelSettings
        }
      }
    }));
  }, []);

  // 更新通用设置
  const updateGeneralSettings = useCallback((generalSettings: Partial<GeneralSettings>) => {
    setState(prev => ({
      ...prev,
      settings: {
        ...prev.settings,
        general: {
          ...prev.settings.general,
          ...generalSettings
        }
      }
    }));
  }, []);

  // 更新高级设置
  const updateAdvancedSettings = useCallback((advancedSettings: Partial<AdvancedSettings>) => {
    setState(prev => ({
      ...prev,
      settings: {
        ...prev.settings,
        advanced: {
          ...prev.settings.advanced,
          ...advancedSettings
        }
      }
    }));
  }, []);

  // 切换API密钥显示状态
  const toggleApiKeyVisibility = useCallback(() => {
    setState(prev => ({ ...prev, showApiKey: !prev.showApiKey }));
  }, []);

  // 测试连接
  const testConnection = useCallback(async (): Promise<boolean> => {
    const { apiUrl, apiKey } = state.settings.model;
    
    // 更新测试状态，清空之前的错误
    setState(prev => ({ 
      ...prev, 
      connectionTestStatus: ConnectionTestStatus.TESTING,
      connectionTestError: undefined
    }));

    try { 
      // 现在只使用自定义模型
      const model = state.settings.model.model || "";

      
      if (!model) {
        throw new Error('模型名称不能为空');
      }
      
      await mockTestConnection(apiUrl, apiKey, model);
      
      // 测试成功
      setState(prev => ({ 
        ...prev, 
        connectionTestStatus: ConnectionTestStatus.SUCCESS,
        connectionTestError: undefined
      }));
      
      return true;
    } catch (error) {
      // 测试出错
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      
      setState(prev => ({ 
        ...prev, 
        connectionTestStatus: ConnectionTestStatus.FAILED,
        connectionTestError: errorMessage
      }));
      
      return false;
    }
  }, [state.settings.model]);

  // 保存设置
  const saveSettings = useCallback(async (): Promise<boolean> => {
    // 更新保存状态为保存中
    setState(prev => ({ 
      ...prev, 
      saveStatus: SaveSettingsStatus.SAVING 
    }));

    try {
      // 调用模拟保存API
      console.log("保存设置:", state.settings);
      const success = await mockSaveSettings(state.settings);
      
      if (success) {
        // 保存成功，更新原始设置
        setState(prev => ({ 
          ...prev, 
          originalSettings: { ...prev.settings },
          hasUnsavedChanges: false,
          saveStatus: SaveSettingsStatus.SUCCESS 
        }));
      } else {
        // 保存失败
        setState(prev => ({ 
          ...prev, 
          saveStatus: SaveSettingsStatus.FAILED 
        }));
      }
      
      return success;
    } catch (error) {
      // 保存出错
      setState(prev => ({ 
        ...prev, 
        saveStatus: SaveSettingsStatus.FAILED 
      }));
      
      return false;
    }
  }, [state.settings]);

  // 重置设置到上次保存的状态
  const resetSettings = useCallback(() => {
    setState(prev => ({ 
      ...prev, 
      settings: { ...prev.originalSettings },
      hasUnsavedChanges: false,
      connectionTestStatus: ConnectionTestStatus.IDLE
    }));
  }, []);

  // 上下文值
  const contextValue: SettingContextType = {
    state,
    openSettings,
    closeSettings,
    setActiveTab,
    updateModelSettings,
    updateGeneralSettings,
    updateAdvancedSettings,
    toggleApiKeyVisibility,
    testConnection,
    saveSettings,
    resetSettings
  };

  return (
    <SettingContext.Provider value={contextValue}>
      {children}
    </SettingContext.Provider>
  );
};

// 自定义钩子，用于访问设置上下文
export const useSettings = (): SettingContextType => {
  const context = useContext(SettingContext);
  if (context === undefined) {
    throw new Error('useSettings must be used within a SettingProvider');
  }
  return context;
};
